package com.fjwt.gz.coupon.tlpay;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.bo.CouponAwardBo;
import com.fjwt.gz.core.third.interfaces.ICheckService;
import com.shopoint.openapis.ClientConfiguration;
import com.shopoint.openapis.OpenApisClient;
import com.shopoint.openapis.common.auth.CredentialsProvider;
import com.shopoint.openapis.common.auth.DefaultCredentialProvider;
import com.shopoint.openapis.model.CouponUseRequest;
import com.shopoint.openapis.model.GenericResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 通联对账单
 */
@Slf4j
@Component
public class TlpayCheckBillService implements ICheckService {
    //TODO  注意：：注意：：上面要记得封装一层，进行分发，到这一层
    //TODO  上面封装的一层自动注入这个service，调用下载账单的方法，然后返回对应的数据，上一层进行不同的通道的处理
    //TODO  注意这个是通联单独的下载的账单接口，上一层要封装一层，通过ifcode进行分发，

    public JSONObject getBill(CouponAwardBo couponAwardBo) {
        log.info("通联下载对账单的进来的参数是：{}", JSONUtil.toJsonStr(couponAwardBo));
        if (ObjectUtils.isEmpty(couponAwardBo.getAuthConfig())) {
            log.info("通联通道配置参数为空: {}", JSONUtil.toJsonStr(couponAwardBo));
            throw new BizException("通联通道配置参数为空");
        }

        try {
            // 批次号
            JSONObject payAuthConfigJson = JSONObject.parseObject(couponAwardBo.getPayConfig());
            Integer couponId = payAuthConfigJson.getInteger("thirdActivityId");
            if (ObjectUtils.isEmpty(couponId)) {
                log.info("通联下载对账单----批次号为空");
                throw new BizException("通联下载对账单-----批次号为空");
            }
            log.info("活动批次号: {}", couponId);

            // 请求通联，拉取账单，响应数据
            BufferedReader reader = authConnect(couponAwardBo.getAuthConfig(), couponId);
            if (ObjectUtils.isEmpty(reader)) {
                log.info("通联下载对账单----通联拉取账单数据为空");
                throw new BizException("通联下载对账单----通联拉取账单数据为空");
            }
            log.info("通联对拉取账单响应的数据为: {}", reader);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("billData", reader);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通联通道连接
     */
    public BufferedReader authConnect(String authConfig, Integer couponId) {
        JSONObject tlAuthConfig = JSONObject.parseObject(authConfig);

        // 请求路径
        String HTTP_URL = tlAuthConfig.getString("url");
        // 数字营销分配的appid
        String appIdRSA2 = tlAuthConfig.getString("appId");
        // AES
        String aesKey = tlAuthConfig.getString("aesKey");
        // 数字营销的RSA2公钥
        String providerPublicKeyRSA2 = tlAuthConfig.getString("publicKey");
        // 对接方的RSA私钥
        String callerPrivateKeyRSA2 = tlAuthConfig.getString("privateKey");
        BufferedReader reader = null;
        try {
            // 创建链接
            CredentialsProvider openApis = new DefaultCredentialProvider(appIdRSA2, providerPublicKeyRSA2, aesKey, callerPrivateKeyRSA2);
            OpenApisClient client = new OpenApisClient(HTTP_URL, openApis, new ClientConfiguration());
            GenericResult result = client.couponServiceCouponUse(new CouponUseRequest(couponId));
            log.info("JSON.toJSONString(result) = :{}", JSON.toJSONString(result));

            JSONObject object = JSONObject.parseObject(JSON.toJSONString(result));

            if (!ObjectUtils.isEmpty(object.getString("url"))) {
                URL url = new URL(object.getString("url"));
                // 打开连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                // 设置请求方法为GET
                connection.setRequestMethod("GET");
                // 设置Auth信息
                connection.setRequestProperty("Authorization", object.getString("authorization"));
                // 获取响应状态码
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 处理响应数据
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                } else {
                    log.info("Error Code: {}", responseCode);
                }
                // 关闭连接
//                connection.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reader;
    }
}

